<?php

namespace Alter\HominemBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use JMS\SecurityExtraBundle\Annotation\Secure;

use Alter\HominemBundle\Form\NewsForm;
use Alter\HominemBundle\Entity\News;
use Alter\UserBundle\Entity\User;

class NewsController extends ContainerAware
{
    public function afficherAction()
    {        
	$em = $this->container->get('doctrine')->getEntityManager();

	$news= $em->getRepository('AlterHominemBundle:News')->findAll();

	return $this->container->get('templating')->renderResponse('AlterHominemBundle:News:afficher.html.twig', 
	array(
	'news' => $news
 	));
     }
    
 

    /**
     * @Secure(roles="ROLE_ADMIN")
     */
    public function editerAction($id = null)
    {
	$message='';
	$em = $this->container->get('doctrine')->getEntityManager();

	if (isset($id)) 
	{
		// modification d'une news existante : on recherche ses données
		$news = $em->find('AlterHominemBundle:News', $id);

		if (!$news)
		{
			$message='Aucune news trouvée';
		}
	}
	else 
	{
		// ajout d'un nouvel acteur
		$news = new News();
	}

	$form = $this->container->get('form.factory')->create(new NewsForm(), $news);

	$user = new User();
	$user = $this->container->get('security.context')->getToken()->getUser();

	$request = $this->container->get('request');
	$news->setDate(new \DateTime());
	$news->setUser($user);

	if ($request->getMethod() == 'POST') 
	{
    	  	$form->bindRequest($request);

           if ($form->isValid()) 
	   {
		$em->persist($news);
		$em->flush();
		if (isset($id)) 
		{
			$message='News modifiée avec succès !';
		}
		else 
		{
			$message='News ajoutée avec succès !';
		}
	   }
	}

	return $this->container->get('templating')->renderResponse(
'AlterHominemBundle:News:editer.html.twig',
	array(
	'form' => $form->createView(),
	'message' => $message,
	));
    }


  public function supprimerAction($id)
  {
    $em = $this->container->get('doctrine')->getEntityManager();
    $news = $em->find('AlterHominemBundle:News', $id);
        
    if (!$news) 
    {
      throw new NotFoundHttpException("News non trouvée");
    }
        
    $em->remove($news);
    $em->flush();        


    return new RedirectResponse($this->container->get('router')->generate('news'));
}
}

